﻿using System;
using System.Collections.Generic;
using System.Text;

using System.Net;
using System.Net.Mail;
using System.Text.RegularExpressions;
using System.Net.Sockets;
using System.IO;
using System.Management;
using System.Diagnostics;
using System.ComponentModel;
namespace Tickz
{
    public class EmailTools
    {
        private string strTestFrom = "879885443@qq.com";
        TcpClient tcpc;
        NetworkStream netStream;
        string strDomain;
        byte[] bb;
        int len;
        string read;
        string stringTosend;
        byte[] arrayToSend;
        bool flag;       
        /// <summary>
        /// 获得邮箱服务器的mx记录
        /// </summary>
        /// <param name="strEmail"></param>
        /// <returns></returns>
        public string getMailServer(string strEmail)
        {
            strDomain = strEmail.Split('@')[1];            
            ProcessStartInfo info = new ProcessStartInfo();   //指定启动进程时使用的一组值。
            info.UseShellExecute = false;
            info.RedirectStandardInput = true;
            info.RedirectStandardOutput = true;
            info.FileName = "nslookup";
            info.CreateNoWindow = true;
            info.Arguments = "-type=mx " + strDomain;
            Process ns = Process.Start(info);        //提供对本地和远程进程的访问并使您能够启动和停止本地系统进程。
            StreamReader sout = ns.StandardOutput;
            Regex reg = new Regex(@"mail exchanger = (?<mailServer>[^\s]+)");
            string strResponse = "";
            while ((strResponse = sout.ReadLine()) != null)
            {
                Match amatch = reg.Match(strResponse);   // Match  表示单个正则表达式匹配的结果。
                if (reg.Match(strResponse).Success)
                {
                    return amatch.Groups["mailServer"].Value;   //获取由正则表达式匹配的组的集合
                }
            }
            return null;
        }
        /// <summary>
        /// 与邮箱服务器建立连接
        /// </summary>
        /// <param name="mailServer"></param>
        /// <returns></returns>
        private bool Connect(string mailServer)
        {
            try
            {
                tcpc.Connect(mailServer, 25);
                netStream = tcpc.GetStream();
                len = netStream.Read(bb, 0, bb.Length);
                read = Encoding.UTF8.GetString(bb);
                if (read.StartsWith("220") == true)
                    return true;
            }
            catch 
            {
               
            }
            return false;
        }
        /// <summary>
        /// 向邮箱服务器 ，发送命令
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        private bool SendCommand(string command)
        {
            try
            {
                arrayToSend = Encoding.UTF8.GetBytes(command.ToCharArray());
                netStream.Write(arrayToSend, 0, arrayToSend.Length);
                len = netStream.Read(bb, 0, bb.Length);
                read = Encoding.UTF8.GetString(bb);   
            }
            catch 
            {
                return false;
            }
            if (read.StartsWith("250"))
                return true;
            else
                return false;
        }
        public string checkEmail(string mailAddress)
        {
            Regex reg = new Regex(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
            if (!reg.IsMatch(mailAddress))
            {                           
                return "邮件格式不正确";
            }//Email地址形式上就不对

            string mailServer = getMailServer(mailAddress);
            if (mailServer == null)
            {    //邮件服务器探测错误      
                return "邮箱服务器不存在";                
            }
           
            tcpc = new TcpClient();      //为 TCP 网络服务提供客户端连接。
            tcpc.NoDelay = true;
            tcpc.ReceiveTimeout = 3000;
            tcpc.SendTimeout = 3000;
            bb = new byte[512];

            try
            {                
                Connect(mailServer);
                string mailServer2 = getMailServer(strTestFrom);
                stringTosend = "helo " + mailServer2 + "\r\n";                
                flag = SendCommand(stringTosend);
                if (flag == false)
                {                   
                    return "发送命令失败";
                }
                stringTosend = "mail from:<" + strTestFrom + ">" + "\r\n"; 
                flag = SendCommand(stringTosend);
                if (flag == false)
                {
                    return "发送命令失败";
                }
                stringTosend = "rcpt to:<" + mailAddress + ">" + "\r\n";               
                flag = SendCommand(stringTosend);
                if (flag == true)
                {   
                   return "邮箱存在";
                }
                else
                {                    
                    return "邮箱用户不存在";
                }
                /*
                stringTosend = "data" + "\r\n";
                this.textBoxShow.Text += "发送：" + stringTosend;
                flag = SendCommand(stringTosend);
                stringTosend = "Subject:wuzhi"+"\r\n"+"\r\n"+"hehe,zhiwu,wanshanghao!" + "\r\n"+"."+"\r\n";
                flag = SendCommand(stringTosend);
                */
            }
            catch
            {
                return "发生错误";   //发生错误或邮件服务器不可达
            }
        }



        private static string stmpServer;

        public static string StmpServer
        {
            get { return EmailTools.stmpServer; }
            set { EmailTools.stmpServer = value; }
        }
        private static string stmpUser;

        public static string StmpUser
        {
            get { return EmailTools.stmpUser; }
            set { EmailTools.stmpUser = value; }
        }
        private static string stmpPass;

        public static string StmpPass
        {
            get { return EmailTools.stmpPass; }
            set { EmailTools.stmpPass = value; }
        }
        /**/
        /// <summary>
        /// 发送Email功能函数
        /// </summary>
        /// <param name="from">发送人</param>
        /// <param name="to">接收人</param>
        /// <param name="cc">抄送</param>
        /// <param name="subject">主题</param>
        /// <param name="body">内容</param>
        /// <param name="isBodyHtml">是否是HTML格式Mail</param>
        /// <returns>是否成功</returns>
        public static bool SendEmail(string from, string to, string cc, string subject, string body, bool isBodyHtml)
        {
            try
            {
                Debug.WriteLine(DateTime.Now);
                
                //设置smtp
                System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(StmpServer);
                //设置帐户
                smtp.Credentials = new NetworkCredential(StmpUser, StmpPass);
                //开一个Message
                System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
                //主题
                mail.Subject = subject;
                mail.SubjectEncoding = System.Text.Encoding.GetEncoding("GB2312");
                mail.BodyEncoding = System.Text.Encoding.GetEncoding("GB2312");
                //发送
                mail.From = new System.Net.Mail.MailAddress(from);
                //邮件等级
                mail.Priority = System.Net.Mail.MailPriority.High;
                //设置邮件格式
                mail.IsBodyHtml = isBodyHtml;
                //主题内容
                mail.Body = body;
                //设置发送对象
                mail.To.Add(to);

                //如果有抄送人就抄送,没有就不送
                if (cc != null && cc != string.Empty)
                {
                    //抄送
                    mail.CC.Add(cc);
                }

                //发送Email
                smtp.SendCompleted += new SendCompletedEventHandler(client_SendCompleted);

                object userState = mail;


                smtp.SendAsync(mail, userState);

                return true;
            }
            catch (Exception ex)
            {

                return false;
            }
        }




        public static void client_SendCompleted(object sender, AsyncCompletedEventArgs e)
        {
            bool mailSent = true;

            System.Net.Mail.MailMessage mail = (System.Net.Mail.MailMessage)e.UserState;
            string subject = mail.Subject;
            string content = mail.Body;

            if (e.Cancelled)
            {
                mailSent = false;
            }
            if (e.Error != null)
            {
                mailSent = false;
            }
            if (!mailSent)
            {
                string file = "Send Mail/Send Mail test asnc Error " + System.DateTime.Now.ToString("yyyy-MM-dd") + ".txt";

                StringBuilder sb = new StringBuilder();
                sb.Append("Send Failed!  ");
                sb.Append("Subject :" + subject + " ");
                sb.Append("Content :" + content);
                sb.Append("Exception :" + e.Error.ToString());

            }
            else
            {
                string file = "Send Mail/Send Mail test asnc Error " + System.DateTime.Now.ToString("yyyy-MM-dd") + ".txt";

                StringBuilder sb = new StringBuilder();
                sb.Append("Send Sucess!  ");
                sb.Append("Subject :" + subject + " ");
                sb.Append("Content :" + content);

            }

        }














    }
}
